"use client"

import { useState, useCallback, useEffect } from 'react'
import type { 
  DialogType, 
  BottomNavigationState, 
  BottomNavigationActions,
  TrackingEvent 
} from '@/lib/types/bottom-navigation'
import { 
  DEFAULT_BOTTOM_NAV_STATE, 
  TRACKING_EVENTS 
} from '@/lib/constants/bottom-navigation'

/**
 * 底部导航状态管理Hook
 * 提供弹窗状态管理和用户交互追踪
 */
export function useBottomNavigation(): BottomNavigationState & BottomNavigationActions {
  // 基础状态管理
  const [state, setState] = useState<BottomNavigationState>(DEFAULT_BOTTOM_NAV_STATE)

  // 用户交互追踪
  const trackInteraction = useCallback((action: string, metadata?: Record<string, any>) => {
    const event: TrackingEvent = {
      action,
      target: 'bottom_navigation',
      timestamp: Date.now(),
      metadata: {
        activeDialog: state.activeDialog,
        ...metadata
      }
    }

    // 在开发环境下输出日志
    if (process.env.NODE_ENV === 'development') {
      console.info('Bottom Navigation Interaction:', event)
    }

    // 这里可以集成实际的分析工具，如Google Analytics, Mixpanel等
    if (typeof window !== 'undefined') {
      // 示例：使用window.gtag或其他分析工具
      // window.gtag?.('event', action, metadata)
    }

    setState(prev => ({
      ...prev,
      lastInteraction: action
    }))
  }, [state.activeDialog])

  // 打开弹窗
  const openDialog = useCallback((dialogType: Exclude<DialogType, null>) => {
    setState(prev => ({
      ...prev,
      activeDialog: dialogType,
      lastInteraction: `open_${dialogType}`
    }))
    
    // 追踪弹窗打开事件
    trackInteraction(TRACKING_EVENTS.DIALOG_OPEN, { dialogType })
  }, [trackInteraction])

  // 关闭弹窗
  const closeDialog = useCallback(() => {
    setState(prev => ({
      ...prev,
      activeDialog: null,
      lastInteraction: 'close_dialog'
    }))
    
    // 追踪弹窗关闭事件
    trackInteraction(TRACKING_EVENTS.DIALOG_CLOSE)
  }, [trackInteraction])

  // 设置加载状态
  const setLoading = useCallback((loading: boolean) => {
    setState(prev => ({
      ...prev,
      isLoading: loading
    }))
  }, [])

  // 键盘事件处理
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      // Escape键关闭弹窗
      if (event.key === 'Escape' && state.activeDialog) {
        event.preventDefault()
        closeDialog()
      }
    }

    // 只在有弹窗打开时添加监听器
    if (state.activeDialog) {
      document.addEventListener('keydown', handleKeyDown)
      
      // 防止滚动穿透
      document.body.style.overflow = 'hidden'
    } else {
      document.body.style.overflow = ''
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown)
      document.body.style.overflow = ''
    }
  }, [state.activeDialog, closeDialog])

  // 返回状态和操作方法
  return {
    ...state,
    openDialog,
    closeDialog,
    setLoading,
    trackInteraction
  }
}

/**
 * 设备能力检测Hook
 * 检测用户设备的各种能力以提供适配的体验
 */
export function useDeviceCapabilities() {
  const [capabilities, setCapabilities] = useState({
    supportsDialog: false,
    supportsHover: false,
    prefersReducedMotion: false,
    connectionSpeed: 'unknown'
  })

  useEffect(() => {
    if (typeof window === 'undefined') return

    const checkCapabilities = () => {
      setCapabilities({
        // 检查是否支持原生dialog元素
        supportsDialog: 'showModal' in HTMLDialogElement.prototype,
        
        // 检查是否支持hover（区分触摸设备）
        supportsHover: window.matchMedia('(hover: hover)').matches,
        
        // 检查是否偏好减少动画
        prefersReducedMotion: window.matchMedia('(prefers-reduced-motion: reduce)').matches,
        
        // 检查网络连接速度
        connectionSpeed: (navigator as any).connection?.effectiveType || 'unknown'
      })
    }

    checkCapabilities()

    // 监听媒体查询变化
    const hoverQuery = window.matchMedia('(hover: hover)')
    const motionQuery = window.matchMedia('(prefers-reduced-motion: reduce)')
    
    hoverQuery.addEventListener('change', checkCapabilities)
    motionQuery.addEventListener('change', checkCapabilities)

    return () => {
      hoverQuery.removeEventListener('change', checkCapabilities)
      motionQuery.removeEventListener('change', checkCapabilities)
    }
  }, [])

  return capabilities
}

/**
 * 性能监控Hook
 * 监控组件渲染性能和用户交互延迟
 */
export function usePerformanceMonitoring(componentName: string = 'BottomNavigation') {
  useEffect(() => {
    if (typeof window === 'undefined' || process.env.NODE_ENV !== 'development') return

    const startTime = performance.now()
    
    return () => {
      const endTime = performance.now()
      const renderTime = endTime - startTime
      
      console.info(`${componentName} render time:`, renderTime.toFixed(2), 'ms')
      
      // 如果渲染时间超过100ms，输出警告
      if (renderTime > 100) {
        console.warn(`${componentName} render time exceeded 100ms:`, renderTime.toFixed(2), 'ms')
      }
    }
  })
} 